﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Stauffware.Common.Core;
using System.Runtime.InteropServices;

namespace Stauffware.Common.IO
{
	/// <summary>
	/// This TextWriter displays its output in a message box when Close() is called.
	/// </summary>
	public class MessageBoxTextWriter : TextWriter
	{
		// Use this to avoid requiring WinForms to be dragged in by  
		// every app that uses Essentials, whether it needs it or not.
		[DllImport("User32.dll", SetLastError=true)]
		private static extern int MessageBox (int parentWindowHandle, string text, string caption, int type );

		private StringBuilder StringBuilder = new StringBuilder();

		/// <inherit/>
		public override Encoding Encoding { get { return Encoding.Unicode; } }
		/// <inherit/>
		public override void Write (string s) { this.StringBuilder.Append(s); }
		/// <inherit/>
		public override void WriteLine (string s) { this.StringBuilder.Append(s + "\r\n"); }
		/// <inherit/>
		public override void Write (char c) { this.StringBuilder.Append(c); }
		/// <inherit/>
		public override void WriteLine ( ) { this.StringBuilder.Append("\r\n"); }

		/// <inherit/>
		public override void Close ( )
		{
			string appName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
			int options = 0;	// OK button (0); info icon (40); application modal (0); 
			MessageBox(0, this.StringBuilder.ToString(), appName, options);
		}
	}
}
